<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      width="80%"
      align-center
      :show-close="false"
      @close="handleClose"
      @open="handleOpen"
      destroy-on-close
      draggable
    >
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>{{ title }}</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close"
            ><CircleCloseFilled color="#fff"
          /></el-icon>
        </div>
      </template>
      <!-- 基本信息 -->
      <div class="bg-white mt-[10px]">
        <BaseHead>基本信息</BaseHead>
        <div class="p-[10px]">
          <el-form :model="editForm" :rules="rules" label-width="130px" ref="editFormRef">
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item label="申请计划名称" prop="name">
                  <el-input placeholder="申请计划名称" clearable v-model="editForm.name"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="项目分类" prop="projectTypeId">
                  <CommonTreeSelect
                    paramsName="项目分类（校级）"
                    placeholder="项目分类"
                    v-model="editForm.projectTypeId"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="申请开始日期" prop="beginDate">
                  <el-date-picker
                    type="date"
                    placeholder="请选择日期"
                    clearable
                    v-model="editForm.beginDate"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="申请结束日期" prop="endDate">
                  <el-date-picker
                    clearable
                    v-model="editForm.endDate"
                    type="date"
                    placeholder="请选择日期"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="到期自动结束" prop="isAutoEnd">
                  <CommonRadio
                    :dataList="booleanList.value"
                    v-model="editForm.isAutoEnd"
                    valueKey="code"
                    :isFetch="false"
                  />
                  <!-- 选择是时显示 -->
                  <div class="w-full" v-if="editForm.isAutoEnd == '1'">
                    申请结束日期当日24时自动停止申报
                  </div>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否可转入评审" prop="isReview">
                  <CommonRadio
                    :dataList="booleanList.value"
                    v-model="editForm.isReview"
                    valueKey="code"
                    :isFetch="false"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="申请指南" prop="fileId">
                  <FileUpload
                    accept=".doc,.docx"
                    :uploadUrl="uploadUrl"
                    v-model="fileList"
                    @change="fileChange"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="备注" prop="note">
                  <el-input type="textarea" clearable v-model="editForm.note"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <el-button type="primary" @click="save">保存</el-button>
            <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import FileUpload from "@/views/project/components/FileUpload.vue";
import CommonRadio from "@/views/project/components/CommonRadio.vue";
import CommonTreeSelect from "@/views/project/components/CommonTreeSelect.vue";
import { addRecords, editRecords, recordsDetail } from "@/api/project/xj/sbxm";
import { ElMessage } from "element-plus";
import { assignObj } from "@/utils/main";
import useCommonFetch from "@/hooks/useCommonFetch";
import dayjs from "dayjs";
const dialogVisible = ref(false);
const editFormRef = ref();
const operateId = ref(null);
const detailData = ref(null);
const uploadUrl = `/commonFile/uploadFile?modelName=xjApply`;
const fileList = ref([]);
const booleanList = ref([]);
const title = computed(() => {
  return operateId.value ? "申报计划编辑" : "申报计划新增";
});
//基本信息表单
const editForm = reactive({
  name: "",
  projectTypeId: "",
  beginDate: "",
  endDate: "",
  isAutoEnd: "0",
  isReview: "0",
  note: "",
  fileId: "",
});
//验证申请开始日期
const validateBeginDate = (rule, value, callback) => {
  if (editForm.endDate) {
    if (new Date(value).getTime() >= new Date(editForm.endDate).getTime()) {
      callback(new Error("申请开始日期必须早于申请结束日期"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
//验证申请结束日期
const validateEndDate = (rule, value, callback) => {
  if (editForm.beginDate) {
    if (new Date(value).getTime() <= new Date(editForm.beginDate).getTime()) {
      callback(new Error("申请结束日期必须晚于申请开始日期"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const rules = reactive({
  name: [
    {
      required: true,
      message: "申请计划名称必填",
    },
  ],
  projectTypeId: [
    {
      required: true,
      message: "项目分类必填",
    },
  ],
  beginDate: [
    {
      required: true,
      message: "申请开始日期必填",
    },
    { validator: validateBeginDate, trigger: "blur" },
  ],
  endDate: [
    {
      required: true,
      message: "申请结束日期必填",
    },
    { validator: validateEndDate, trigger: "blur" },
  ],
  fileId: [
    {
      required: true,
      message: "请上传申请指南",
    },
  ],
});
const emit = defineEmits(["save-success"]);
//获取数据详情
const getDetail = async () => {
  const params = {
    id: operateId.value,
  };
  try {
    const res = await recordsDetail(params);
    detailData.value = res.data;
    //附件列表赋值
    const files = res.data.fileList ? res.data.fileList : [];
    fileList.value = files.map((item) => {
      return {
        name: item.fileName,
        id: item.id,
      };
    });
  } catch (error) {
    console.log(error);
  }
};
// 新增
const add = async () => {
  operateId.value = null;
  dialogVisible.value = true;
};
// 编辑
const edit = async (id) => {
  operateId.value = id;
  dialogVisible.value = true;
  await getDetail();
  nextTick(() => {
    //基础信息赋值
    assignObj(editForm, detailData.value);
    //日期毫秒数处理成字符串格式
    editForm.beginDate = dayjs(editForm.beginDate).format("YYYY-MM-DD");
    editForm.endDate = dayjs(editForm.endDate).format("YYYY-MM-DD");
  });
};
defineExpose({ add, edit });
//点击保存
const save = () => {
  try {
    editFormRef.value?.validate(async (valid) => {
      if (valid) {
        let res;
        let params = {
          ...editForm,
        };
        if (operateId.value) {
          params.id = operateId.value;
          res = await editRecords(params);
        } else {
          res = await addRecords(params);
        }
        if (res.code === 200) {
          ElMessage({
            message: "操作成功！",
            type: "success",
          });
          dialogVisible.value = false;
          emit("save-success");
        }
      }
    });
  } catch (error) {
    console.log(error);
  }
};
const handleOpen = () => {
  booleanList.value = useCommonFetch("是或否（存储值：1/0）");
};
//关闭弹窗
const handleClose = () => {
  //重置基本信息表单数据和评审标准信息数据
  editFormRef.value.resetFields();
  //清空fileList
  fileList.value = [];
};
//上传的文件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id;
    return id;
  });
  editForm.fileId = ids.join(",");
};
</script>

<style scoped lang="scss">
@import url("@/views/project/index.scss");
</style>
